<template>
  <div class="p-3 flex h-full">
    <div class="w-15/20 flex flex-col h-full">
      <!-- <GrowCard /> -->
      <div class="flex mb-1">
        <div class="w-1/1 mr-1"><DeviceCard :datalist="device" /></div>
        <div class="w-1/1"><DeviceCard :datalist="alerts" /></div>
      </div>
      <div class="flex">
        <div class="w-1/1 mr-1"><InstrumentCard :datalist="meter" /></div>
        <div class="w-1/1">
          <InstrumentCard
            :datalist="operation"
            @time-value-select="getTimeValue"
            @tabs-change="handleTabsChange"
            :echartsList="echartsList"
          />
        </div>
      </div>
      <div class="flex mt-1 flex-1">
        <div class="w-1/1 mr-1 flex-1"><UsageCard :datalist="link" /></div>
        <div class="w-1/1 mr-1 flex-1"><UsageCard :datalist="document" /></div>
        <div class="w-1/1 mr-1 flex-1"><UsageCard :datalist="usage" /></div>
      </div>
    </div>
    <div class="w-5/20 ml-1 h-full"><StartUsingCard /> </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted, onBeforeUnmount } from 'vue';
  import DeviceCard from './DeviceCard.vue';
  import InstrumentCard from './InstrumentCard.vue';
  import UsageCard from './UsageCard.vue';
  import StartUsingCard from './StartUsingCard.vue';
  import dayjs from 'dayjs';
  import { useWebsocketStoreWithOut } from '/@/store/modules/thingsboard/websocket';

  const ws = useWebsocketStoreWithOut();

  let echartsList = ref<any>([]);
  const device = ref<any>({
    name: '设备',
    key: 'device',
    canGo: true,
    ant: true,
    value: [
      { title: '活动', num: '10' },
      { title: '未活动', num: '20' },
      { title: '总数', num: '30' },
    ],
  });
  const alerts = ref<any>({
    name: '警报',
    canGo: true,
    key: 'alarm',
    ant: false,
    value: [
      { title: '严重', num: '10' },
      { title: '分配给我', num: '20' },
      { title: '总数', num: '30' },
    ],
  });
  const meter = ref<Object>({
    name: '仪表盘',
    canGo: true,
    key: 'dashboard',
    ant: true,
  });
  const operation = ref<Object>({
    name: '活动',
    canGo: false,
    ant: false,
    tabsant: [
      { title: '设备', id: 1 },
      { title: '传输信息', id: 2 },
    ],
  });
  const link = ref<Object>({
    name: '快速链接',
    canGo: false,
    canEdit: true,
    ant: 1,
  });
  const document = ref<Object>({
    name: '文档',
    canGo: false,
    canEdit: true,
    ant: 2,
  });
  const usage = ref<Object>({
    name: '用法',
    canGo: false,
    ant: 3,
    tabsant: [
      { title: '实体', id: 1 },
      { title: 'API调用', id: 2 },
    ],
  });

  // 订阅设备告警数量数据
  const handleGetDeviceAndAlarmData = () => {
    let sendMsg = {
      entityCountCmds: [
        {
          query: {
            entityFilter: {
              type: 'entityType',
              resolveMultiple: true,
              entityType: 'DEVICE',
            },
            keyFilters: [
              {
                key: {
                  type: 'SERVER_ATTRIBUTE',
                  key: 'active',
                },
                valueType: 'BOOLEAN',
                predicate: {
                  operation: 'EQUAL',
                  value: {
                    defaultValue: false,
                    dynamicValue: null,
                  },
                  type: 'BOOLEAN',
                },
              },
            ],
          },
          cmdId: ws.getAndIncrementCmdId(),
        },
        {
          query: {
            entityFilter: {
              type: 'entityType',
              resolveMultiple: true,
              entityType: 'DEVICE',
            },
            keyFilters: [
              {
                key: {
                  type: 'SERVER_ATTRIBUTE',
                  key: 'active',
                },
                valueType: 'BOOLEAN',
                predicate: {
                  operation: 'EQUAL',
                  value: {
                    defaultValue: true,
                    dynamicValue: null,
                  },
                  type: 'BOOLEAN',
                },
              },
            ],
          },
          cmdId: ws.getAndIncrementCmdId(),
        },
        {
          query: {
            entityFilter: {
              type: 'entityType',
              resolveMultiple: true,
              entityType: 'DEVICE',
            },
          },
          cmdId: ws.getAndIncrementCmdId(),
        },
      ],
      alarmCountCmds: [
        {
          query: {
            severityList: ['CRITICAL'],
            statusList: ['ACTIVE'],
            searchPropagatedAlarms: false,
          },
          cmdId: ws.getAndIncrementCmdId(),
        },
        {
          query: {
            statusList: ['ACTIVE'],
            searchPropagatedAlarms: false,
            assigneeId: {
              entityType: 'USER',
              id: '5b2e7e60-9b1b-11ee-9f1d-2f70aa1d7dac',
            },
          },
          cmdId: ws.getAndIncrementCmdId(),
        },
        {
          query: {
            statusList: ['ACTIVE'],
            searchPropagatedAlarms: false,
          },
          cmdId: ws.getAndIncrementCmdId(),
        },
      ],
    };
    const cmdId1 = ws.getCmdId;
    const cmdIdArr: number[] = [];
    for (let i = 0; i < 8; i++) {
      cmdIdArr.unshift(cmdId1 - i);
    }
    ws.send(cmdIdArr, sendMsg, (data) => {
      if (data.cmdUpdateType === 'COUNT_DATA') {
        if (data.cmdId === cmdId1 - 5) {
          device.value.value[0].num = data.count;
        } else if (data.cmdId === cmdId1 - 4) {
          device.value.value[1].num = data.count;
        } else if (data.cmdId === cmdId1 - 3) {
          device.value.value[2].num = data.count;
        }
      } else if (data.cmdUpdateType === 'ALARM_COUNT_DATA') {
        if (data.cmdId === cmdId1 - 2) {
          alerts.value.value[0].num = data.count;
        } else if (data.cmdId === cmdId1 - 1) {
          alerts.value.value[1].num = data.count;
        } else if (data.cmdId === cmdId1) {
          alerts.value.value[2].num = data.count;
        }
      }
    });
  };

  // 订阅活动-设备数据
  const handleGetDeviceData = () => {
    let sendMsg1 = {
      entityDataCmds: [
        {
          query: {
            entityFilter: {
              type: 'apiUsageState',
              resolveMultiple: true,
            },
            pageLink: {
              pageSize: 1024,
              page: 0,
              sortOrder: {
                key: {
                  type: 'ENTITY_FIELD',
                  key: 'createdTime',
                },
                direction: 'DESC',
              },
            },
            entityFields: [
              {
                type: 'ENTITY_FIELD',
                key: 'name',
              },
              {
                type: 'ENTITY_FIELD',
                key: 'label',
              },
              {
                type: 'ENTITY_FIELD',
                key: 'additionalInfo',
              },
            ],
            latestValues: [],
          },
          cmdId: ws.getAndIncrementCmdId(),
        },
      ],
    };
    ws.send(ws.getCmdId, sendMsg1);
    let sendMsg2 = {
      entityDataCmds: [
        {
          cmdId: ws.getCmdId,
          historyCmd: {
            keys: ['activeDevicesCountHourly'],
            startTs: new Date().getTime() - 30 * 24 * 60 * 60 * 1000,
            endTs: new Date().getTime(),
            interval: 24 * 60 * 60 * 1000,
            limit: 30,
            agg: 'SUM',
          },
        },
      ],
    };
    ws.send(ws.getCmdId, sendMsg2, (data) => {
      if (data.cmdUpdateType === 'ENTITY_DATA' && data.update) {
        let list: any[] = [];
        data.update[0].timeseries.activeDevicesCountHourly.forEach((item) => {
          list.push([dayjs(item.ts).format('YYYY-MM-DD HH:mm:ss'), item.value]);
        });
        echartsList.value = list;
      }
    });
  };

  // 订阅活动-传输消息数据
  const handleGetTransferData = () => {
    let send1 = {
      entityDataCmds: [
        {
          query: {
            entityFilter: {
              type: 'apiUsageState',
              resolveMultiple: true,
            },
            pageLink: {
              pageSize: 1024,
              page: 0,
              sortOrder: {
                key: {
                  type: 'ENTITY_FIELD',
                  key: 'createdTime',
                },
                direction: 'DESC',
              },
            },
            entityFields: [
              {
                type: 'ENTITY_FIELD',
                key: 'name',
              },
              {
                type: 'ENTITY_FIELD',
                key: 'label',
              },
              {
                type: 'ENTITY_FIELD',
                key: 'additionalInfo',
              },
            ],
            latestValues: [],
          },
          cmdId: ws.getAndIncrementCmdId(),
        },
      ],
    };
    ws.send(ws.getCmdId, send1);
    let send2 = {
      entityDataCmds: [
        {
          cmdId: ws.getCmdId,
          historyCmd: {
            keys: ['transportMsgCountHourly'],
            startTs: new Date().getTime() - 30 * 24 * 60 * 60 * 1000,
            endTs: new Date().getTime(),
            interval: 24 * 60 * 60 * 1000,
            limit: 30,
            agg: 'SUM',
          },
        },
      ],
    };
    ws.send(ws.getCmdId, send2, (data) => {
      if (data.cmdUpdateType === 'ENTITY_DATA' && data.update) {
        let list: any[] = [];
        data.update[0].timeseries.transportMsgCountHourly.forEach((item) => {
          list.push([dayjs(item.ts).format('YYYY-MM-DD HH:mm:ss'), item.value]);
        });
        echartsList.value = list;
      }
    });
  };

  onMounted(() => {
    // 初始化 设备、告警数据
    handleGetDeviceAndAlarmData();
    // 初始化 活动-设备数据
    handleGetDeviceData();
  });

  onBeforeUnmount(() => {
    // 断开ws
    ws.close(['telemetry']);
  });

  function getTimeValue(_value) {
    // sendParams.value.entityDataCmds[0].historyCmd.startTs = value[0].valueOf();
    // sendParams.value.entityDataCmds[0].historyCmd.endTs = value[1].valueOf();
    // send(JSON.stringify(sendParams.value));
  }

  function handleTabsChange(id: number) {
    if (id === 2) {
      handleGetTransferData();
    } else if (id === 1) {
      handleGetDeviceData();
    }
  }
</script>
